在Tomcat運行時你總會希望當Tomcat做什麼的時候它可以順便幫你做點什麼,最常見的莫過當ServletContext建立的時候也順便建立DB連線池資訊,讓你的服務一運行就有DB物件可供調用。
Java EE定義了Event讓container中的物件在不同的生命週期時發布event讓註冊的對應事件的監聽器可以進行執行預定的行為,以下是在官方文件中整理出來的事件與監聽器:
web.xml
  <listener>
    <listener-class>com.swj.xml.DemoListener</listener-class>
  </listener>
或是適用annotation
@WebListener
以下Demo ServletContextListener、ServletContextAttributeListener,其餘使用類似
@WebListener
public class DemoListener implements ServletContextListener, ServletContextAttributeListener {
    //ServletContextListener
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContext初始化好了");
    }
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContext銷毀了");
    }
    //ServletContextAttributeListener
    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        System.out.println("添加屬性:"+ event.getName()+",屬性值:"+event.getValue());
    }
    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
        System.out.println("移除屬性:"+ event.getName()+",屬性值:"+event.getValue());
    }
    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        System.out.println("取代屬性:"+ event.getName()+",屬性值:"+event.getValue());
    }
}
DemoServlet
@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getServletContext().setAttribute("msg", "Hello World1111");
        getServletContext().setAttribute("msg", "Hello World2222");
        getServletContext().removeAttribute("msg");
    }
}
訪問DemoServlet後關閉tomcat